<template>
  <div class="app-container-flex">
    <NewFullScreen v-model="showDialog" :title="title">
      <template v-slot:full-button>
        <el-button @click="save">保存</el-button>
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <PageForm
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            v-model:data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
          </PageForm>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('detailInfo') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <NewPageFilter
            :filter-list="filterInfo.searchList"
            :filter-btn="filterInfo.searchBtn"
          >
            <template v-slot:filter-view>
              <el-input
                v-model="tableKey"
                style="width: 500px"
                disabled
              ></el-input>
            </template>
            <template v-slot:filter-search>
              <el-button
                :disabled="!formInfo.data.viewName || !formInfo.data.tableKey"
                @click="getConfig"
                >获取最新配置项</el-button
              >
            </template>
            <template v-slot:filter-init>
              <el-button
                :disabled="!formInfo.data.viewName || !formInfo.data.tableKey"
                @click="getInitConfig"
                >获取初始配置项</el-button
              >
            </template>
            <template v-slot:filter-commonConfig>
              <el-select
                v-model="filterInfo.commonConfig"
                placeholder="请选择合并规格"
              >
                <el-option
                  v-for="(item, index) in filterInfo.options"
                  :key="index"
                  :label="item.name"
                  :value="item.code"
                >
                </el-option>
              </el-select>
              <el-button @click="setCommonConfig">设置</el-button>
            </template>
          </NewPageFilter>
          <div class="flex_full_item">
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <el-table
                :id="tableId"
                :height="tableContainerHeight + 'px'"
                :data="tableInfo.data"
                border
                style="width: 100%"
              >
                <el-table-column label="序号" fixed="left" width="45">
                  <template #default="scope">{{ scope.$index + 1 }}</template>
                </el-table-column>
                <el-table-column
                  label="字段名"
                  fixed="left"
                  align="center"
                  prop="fieldName"
                  min-width="10%"
                  show-overflow-tooltip
                >
                </el-table-column>
                <el-table-column
                  label="字段名(数据库)"
                  fixed="left"
                  align="center"
                  prop="columnName"
                  min-width="10%"
                  show-overflow-tooltip
                >
                </el-table-column>
                <el-table-column
                  label="列名"
                  align="center"
                  fixed="left"
                  min-width="10%"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.label"
                      placeholder="请输入列名"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  fixed="left"
                  min-width="8%"
                  show-overflow-tooltip
                >
                  <template #header>
                    <span
                      >是否返回
                      <el-tooltip placement="top" effect="light">
                        <template #content>
                          <span v-html="'0 返回 1 不返回'"></span>
                        </template>
                        <el-icon><QuestionFilled /></el-icon> </el-tooltip
                    ></span>
                  </template>
                  <template #default="scope">
                    <el-switch
                      v-model="scope.row.isBack"
                      :disabled="scope.row.isBack === -2"
                      :active-value="0"
                      :inactive-value="1"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  fixed="left"
                  min-width="8%"
                  show-overflow-tooltip
                >
                  <template #header>
                    <span
                      >是否展示<el-tooltip placement="top" effect="light">
                        <template #content>
                          <span
                            v-html="
                              '-2 不展示 不可修改;-1 不展示 用户不可配置;0 不展示 用户可配置;>0 按照顺序展示'
                            "
                          ></span>
                        </template>
                        <el-icon><QuestionFilled /></el-icon></el-tooltip
                    ></span>
                  </template>
                  <template #default="scope">
                    <input
                      v-model.lazy="scope.row.showLevel"
                      class="el-input el-input--mini input"
                      :disabled="scope.row.showLevel === -2"
                      type="number"
                    />
                  </template>
                </el-table-column>

                <el-table-column
                  align="center"
                  fixed="left"
                  min-width="8%"
                  show-overflow-tooltip
                >
                  <template #header>
                    <span
                      >分组查询<el-tooltip placement="top" effect="light">
                        <template #content>
                          <span
                            v-html="
                              '>1 按照顺序展示分组条件 0，-1，-2 不能分组查询不可配置'
                            "
                          ></span>
                        </template>
                        <el-icon><QuestionFilled /></el-icon></el-tooltip
                    ></span>
                  </template>
                  <template #default="scope">
                    <input
                      v-model.lazy="scope.row.groupLevel"
                      class="el-input el-input--mini input"
                      :disabled="scope.row.groupLevel === -2"
                      type="number"
                    />
                  </template>
                </el-table-column>

                <el-table-column
                  align="center"
                  fixed="left"
                  min-width="8%"
                  show-overflow-tooltip
                >
                  <template #header>
                    <span
                      >排序控制<el-tooltip placement="top" effect="light">
                        <template #content>
                          <span
                            v-html="
                              '（可排序字段的查询方式必须是数据库匹配）-2 不排序，不可修改;-1 不排序,用户不可配置;0 不排序 用户可配置是否排序; 1 升序 2 降序'
                            "
                          ></span>
                        </template>
                        <el-icon><QuestionFilled /></el-icon></el-tooltip
                    ></span>
                  </template>
                  <template #default="scope">
                    <input
                      v-model.lazy="scope.row.sortControllerType"
                      class="el-input el-input--mini input"
                      :disabled="scope.row.sortControllerType === -2"
                      type="number"
                    />
                  </template>
                </el-table-column>

                <el-table-column
                  align="center"
                  fixed="left"
                  min-width="8%"
                  show-overflow-tooltip
                >
                  <template #header>
                    <span
                      >排序顺序<el-tooltip placement="top" effect="light">
                        <template #content>
                          <span v-html="'排序优先级 1,2,3,4,5,6,7,8,9'"></span>
                        </template>
                        <el-icon><QuestionFilled /></el-icon></el-tooltip
                    ></span>
                  </template>
                  <template #default="scope">
                    <input
                      v-model.lazy="scope.row.sortLevel"
                      :disabled="scope.row.sortLevel === -2"
                      class="el-input el-input--mini input"
                      type="number"
                    />
                  </template>
                </el-table-column>

                <el-table-column
                  align="center"
                  fixed="left"
                  min-width="8%"
                  show-overflow-tooltip
                >
                  <template #header>
                    <span
                      >查询控制<el-tooltip placement="top" effect="light">
                        <template #content>
                          <span
                            v-html="
                              '-2 查询条件不展示，不可修改;-1 查询条件不展示，用户不可配置;0 查询条件不展示 用户可配置; >0 查询条件展示，并按照顺序值顺序展示'
                            "
                          ></span>
                        </template>
                        <el-icon><QuestionFilled /></el-icon></el-tooltip
                    ></span>
                  </template>
                  <template #default="scope">
                    <input
                      v-model.lazy="scope.row.searchLevel"
                      :disabled="scope.row.searchLevel === -2"
                      class="el-input el-input--mini input"
                      type="number"
                    />
                  </template>
                </el-table-column>

                <el-table-column
                  align="center"
                  fixed="left"
                  min-width="8%"
                  show-overflow-tooltip
                >
                  <template #header>
                    <span>匹配类型</span>
                  </template>
                  <template #default="scope">
                    <select
                      v-model.lazy="scope.row.queryType"
                      :disabled="scope.row.queryType === -2"
                      class="select"
                    >
                      <option
                        v-for="(item, index) in queryTypeOption"
                        :key="index"
                        :value="item.code"
                      >
                        {{ item.name }}
                      </option>
                    </select>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  fixed="left"
                  min-width="8%"
                  show-overflow-tooltip
                >
                  <template #header>
                    <span
                      >后端合并<el-tooltip placement="top" effect="light">
                        <template #content>
                          <span v-html="'0不合并 >=1 按照值顺序合并'"></span>
                        </template>
                        <el-icon><QuestionFilled /></el-icon></el-tooltip
                    ></span>
                  </template>
                  <template #default="scope">
                    <input
                      v-model.lazy="scope.row.sysGroupLevel"
                      :disabled="scope.row.sysGroupLevel === -2"
                      class="el-input el-input--mini input"
                      type="number"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  fixed="left"
                  min-width="8%"
                  show-overflow-tooltip
                >
                  <template #header>
                    <span
                      >是否聚合<el-tooltip placement="top" effect="light">
                        <template #content>
                          <span
                            v-html="'0 不使用 1求和 2最大值 3最小值 4平均值'"
                          ></span>
                        </template>
                        <el-icon><QuestionFilled /></el-icon></el-tooltip
                    ></span>
                  </template>
                  <template #default="scope">
                    <select
                      v-model.lazy="scope.row.functionType"
                      :disabled="scope.row.functionType === -2"
                      class="select"
                    >
                      <option
                        v-for="(item, index) in functionTypeOption"
                        :key="index"
                        :value="item.code"
                      >
                        {{ item.name }}
                      </option>
                    </select>
                  </template>
                </el-table-column>
                <el-table-column
                  label="列表单元格宽度"
                  align="center"
                  fixed="left"
                  min-width="10%"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.formWidth"
                      placeholder="请输入列表单元格宽度"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  label="EXCEL单元格宽度"
                  align="center"
                  fixed="left"
                  min-width="10%"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.excelWidth"
                      placeholder="请输入EXCEL单元格宽度"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  label="打印单元格宽度"
                  align="center"
                  fixed="left"
                  min-width="10%"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.printWidth"
                      placeholder="请输入打印单元格宽度"
                    ></el-input>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
  </div>
</template>

<script setup name="customizeModify">
import _ from 'lodash'
import {
  updateCustomize,
  customizeGetSetting,
  customizeGetInitSetting,
  getCustomizeById,
  getCustomizeSysSettingList,
} from '@/api/customize.js'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const store = useStore()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: Object,
    default: () => {
      return ''
    },
  },
  id: {
    type: Object,
    default: () => {
      return ''
    },
  },
})
const formRefs = ref('')
const filterInfo = ref({
  commonConfig: '',
  searchList: [{ slot: true, value: 'view' }],
  searchBtn: [
    { type: 'slot', value: 'search' },
    { type: 'slot', value: 'init' },
    { type: 'slot', value: 'commonConfig' },
  ],
  options: store.state.permission.dict['customize_common_config'] || [],
})
const tableInfo = ref({
  data: [],
  rowIndex: -1, //行索引
  columnIndex: -1, //列索引
  fieldList: [
    {
      label: '字段名',
      value: 'fieldName',
      fixed: 'left',
      minWidth: '8%',
    },
    {
      label: '字段名(数据库)',
      value: 'columnName',
      fixed: 'left',
      minWidth: '8%',
    },
    {
      label: '列名',
      value: 'label',
      type: 'input',
      fixed: 'left',
      minWidth: '8%',
    },
    {
      label: '是否返回',
      value: 'isBack',
      type: 'slot',
      labelTip: '0 返回 1 不返回 默认 0',
      fixed: 'left',
      minWidth: '6%',
    },
    {
      type: 'slot',
      label: '是否展示',
      value: 'showLevel',
      labelTip: '-1 不展示 0 展示 用户可配置 1 展示，顺1 默认0',
      minWidth: '8%',
    },
    {
      type: 'slot',
      label: '分组查询',
      value: 'groupLevel',
      labelTip: '-1 不分组 0 可分组 用户可配置 1 分组，顺1 默认0',
      minWidth: '8%',
    },
    {
      type: 'slot',
      label: '排序控制',
      value: 'sortControllerType',
      labelTip:
        ' （可排序字段的查询方式必须是数据库匹配）-1 不可排序 0 可排序 用户可配置 1 升序 2 降序 默认0',
      minWidth: '8%',
    },
    {
      type: 'slot',
      label: '排序顺序',
      value: 'sortLevel',
      labelTip: '排序优先级 1,2,3,4,5,6,7,8,9 默认0',
      minWidth: '6%',
    },
    {
      type: 'slot',
      label: '查询控制',
      value: 'searchLevel',
      labelTip: ' -1 不可作为查询条件 0 可做条件 用户可配置 1 顺序1查询条件',
      minWidth: '7%',
    },
    {
      type: 'slot',
      label: '匹配类型',
      value: 'queryType',
      labelTip: '',
      minWidth: '8%',
    },
    {
      type: 'slot',
      label: '后端合并',
      value: 'sysGroupLevel',
      labelTip: '0不合并 1合并顺1  默认0',
      minWidth: '8%',
    },
    {
      type: 'slot',
      label: '是否聚合',
      value: 'functionType',
      labelTip: '0 不使用 1SUM 2 MAX 3 MIN 4 AVG',
      minWidth: '8%',
    },
    {
      label: '表格单元格宽度',
      value: 'formWidth',
      type: 'input',
      fixed: 'left',
      minWidth: '5%',
    },
    {
      label: '下载Excel单元格宽度',
      value: 'excelWidth',
      type: 'input',
      fixed: 'left',
      minWidth: '5%',
    },
    {
      label: '打印表格单元格宽度',
      value: 'printWidth',
      type: 'input',
      fixed: 'left',
      minWidth: '5%',
    },
  ],
})
const formInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    { label: '名称', value: 'name', type: 'input', disabled: false },
    {
      label: '表格-key',
      value: 'tableKey',
      type: 'input',
      disabled: false,
    },
    {
      label: '排序方式',
      value: 'sortType',
      type: 'select-model',
      disabled: false,
      clearable: true,
      code: 'sort_type',
    },
    {
      label: '表格设置类型',
      value: 'tableSetType',
      type: 'select-model',
      code: 'table_set_type',
      show: true,
    },
    {
      label: 'view对象',
      value: 'viewName',
      type: 'textarea',
      disabled: false,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    tableKey: [{ required: true, message: '请输入表格-key', trigger: 'blur' }],
    sortType: [
      { required: true, message: '请选择排序方式', trigger: 'change' },
    ],
    tableSetType: [
      { required: true, message: '请选择是否编辑', trigger: 'change' },
    ],
    viewName: [{ required: true, message: '请输入view对象', trigger: 'blur' }],
  },
})
const tableKey = ref('')
const queryTypeOption = ref(store.state.permission.dict['determine_term'] || [])
const functionTypeOption = ref(
  store.state.permission.dict['function_type'] || []
)
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    emits('update:visible', val) // 更新父组件visible
  },
})
const tableContainerHeight = ref('')
const topHeight = ref('')
const tableId = ref(`page-table-container-height-${_.uniqueId()}`)
watch(
  () => formInfo.value.data.tableKey,
  (val) => {
    if (val) {
      tableKey.value = val + '-' + (formInfo.value.data.viewName || '')
    }
  },
  {
    deep: true,
  }
)
watch(
  () => formInfo.value.data.viewName,
  (val) => {
    if (val) {
      tableKey.value = (formInfo.value.data.tableKey || '') + '-' + val
    }
  },
  {
    deep: true,
  }
)
watch(
  () => proxy.$store.state.app.pageTableHeightStatus,
  () => {
    setStyle()
  }
)

onMounted(() => {
  proxy.$nextTick(() => {
    setStyle()
  })
  window.onresize = () => {
    setStyle()
  }
  if (props.id) {
    formInfo.value.fieldList.forEach((item) => {
      if (
        item.value !== 'remark' &&
        item.value !== 'sortType' &&
        item.value !== 'name' &&
        item.value !== 'tableSetType'
      ) {
        item.disabled = true
      }
      if (item.value === 'tableSetType') {
        item.show = false
      }
    })
    getMain()
  }
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
})

function setStyle() {
  proxy.$nextTick(() => {
    topHeight.value = document
      .getElementById(tableId.value)
      ?.getBoundingClientRect().top
    tableContainerHeight.value =
      document.body.clientHeight - topHeight.value - 30
  })
}
async function setCommonConfig() {
  let commonConfig = filterInfo.value.commonConfig
  let reList = []
  if (!commonConfig) {
    proxy.$message({
      type: 'warning',
      duration: 3500,
      showClose: true,
      message: '请选择合并规格',
    })
    return
  }
  let arr = await proxy.$fn.splitArr(commonConfig)
  await tableInfo.value.data.forEach((item) => {
    arr.forEach((row) => {
      if (item.fieldName === row && item.sysGroupLevel === -2) {
        reList.push(row)
      }
    })
  })
  if (reList.length) {
    proxy.$message({
      type: 'warning',
      duration: 3500,
      showClose: true,
      message: `${reList}不能作为后端合并条件`,
    })
    return
  }
  await tableInfo.value.data.forEach((item) => {
    if (commonConfig === 'null') {
      item.sysGroupLevel = 0
      item.functionType = '0'
    } else if (commonConfig && commonConfig !== 'null') {
      item.sysGroupLevel = 0
      item.functionType = '0'
      if (arr.length) {
        if (
          item.fieldName.search('qty') !== -1 ||
          item.fieldName.search('Qty') !== -1 ||
          item.fieldName.search('Amount') !== -1
        ) {
          if (
            item.fieldName !== 'qtyOperateMode' &&
            item.fieldName !== 'qtyOperateModeValue'
          ) {
            item.functionType = '1'
          }
        }
        if (arr.includes(item.fieldName)) {
          arr.forEach((row, index) => {
            if (row === item.fieldName) {
              item.sysGroupLevel = index + 1
            }
          })
        }
      }
    }
  })
  proxy.$message({
    type: 'success',
    duration: 3500,
    showClose: true,
    message: '设置成功',
  })
}
function getMain() {
  getCustomizeById(props.id).then((res) => {
    if (res && res.success) {
      formInfo.value.data = {
        ...res.data,
        sortType: res.data.sortType + '',
      }
      getList()
    }
  })
  // this.getConfig()
}
function getList() {
  let _tableInfo = tableInfo.value
  getCustomizeSysSettingList({
    customizeSettingId: props.id,
    sort: 'sort asc',
  }).then((res) => {
    if (res && res.success) {
      let details = res.data
      details.forEach((item) => {
        if (item.queryType === '' || item.queryType === undefined) {
          if (
            item.fieldType === 'LocalDateTime' ||
            item.fieldType === 'LocalDate'
          ) {
            item.queryType = 'BETWEEN'
          } else if (
            item.fieldType === 'Integer' ||
            item.fieldType === 'BigDecimal'
          ) {
            item.queryType = 'ALL_LIKE'
          } else if (item.fieldType === 'String') {
            item.queryType = 'EQUALS'
          }
        }
        if (item.queryCategory === '' || item.queryCategory === undefined) {
          item.queryCategory = 'AND'
        }
      })
      _tableInfo.data = details
    }
  })
}

function getConfig() {
  let _formInfo = formInfo.value
  let _tableInfo = tableInfo.value
  let param = {
    tableKey: _formInfo.data.tableKey + '-' + _formInfo.data.viewName,
  }
  customizeGetSetting(param).then((res) => {
    if (res && res.success) {
      let details = res.data.detail
      details.forEach((item) => {
        if (item.queryType === '' || item.queryType === undefined) {
          if (
            item.fieldType === 'LocalDateTime' ||
            item.fieldType === 'LocalDate'
          ) {
            item.queryType = 'BETWEEN'
          } else if (
            item.fieldType === 'Integer' ||
            item.fieldType === 'BigDecimal'
          ) {
            item.queryType = 'ALL_LIKE'
          } else if (item.fieldType === 'String') {
            item.queryType = 'EQUALS'
          }
        }
        if (item.queryCategory === '' || item.queryCategory === undefined) {
          item.queryCategory = 'AND'
        }
      })
      _tableInfo.data = details
    }
  })
}
function getInitConfig() {
  let _formInfo = formInfo.value
  let _tableInfo = tableInfo.value
  let param = {
    tableKey: _formInfo.data.tableKey + '-' + _formInfo.data.viewName,
  }
  customizeGetInitSetting(param).then((res) => {
    if (res && res.success) {
      let details = res.data.detail
      details.forEach((item) => {
        if (item.queryType === '' || item.queryType === undefined) {
          if (
            item.fieldType === 'LocalDateTime' ||
            item.fieldType === 'LocalDate'
          ) {
            item.queryType = 'BETWEEN'
          } else if (
            item.fieldType === 'Integer' ||
            item.fieldType === 'BigDecimal'
          ) {
            item.queryType = 'ALL_LIKE'
          } else if (item.fieldType === 'String') {
            item.queryType = 'EQUALS'
          }
        }
        if (item.queryCategory === '' || item.queryCategory === undefined) {
          item.queryCategory = 'AND'
        }
      })
      _tableInfo.data = details
    }
  })
}
function save() {
  let _formInfo = formInfo.value
  let _tableInfo = tableInfo.value
  _formInfo.ref.validate((valid) => {
    if (valid) {
      let itemList = _tableInfo.data.filter((item) => {
        return (
          item.label === '' ||
          item.showLevel === '' ||
          item.groupLevel === '' ||
          item.sortControllerType === '' ||
          item.sortLevel === '' ||
          item.searchLevel === '' ||
          item.queryType === '' ||
          item.sysGroupLevel === '' ||
          item.functionType === ''
        )
      })
      if (itemList.length) {
        proxy.$message({
          duration: 3500,
          type: 'warning',
          showClose: true,
          message: '你还有未处理完的项，请处理完',
        })
        return
      }
      let param = {
        head: { ..._formInfo.data },
      }
      if (_tableInfo.data.length) {
        param.detail = _tableInfo.data
      }
      updateCustomize(param).then((res) => {
        if (res && res.success) {
          showDialog.value = false
          emits('returnBack')
        }
      })
    }
  })
}
</script>

<style scoped lang="scss">
.select {
  width: 100%;
  height: 28px;
  padding: 0 15px;
  box-sizing: border-box;
  border-radius: 4px;
  color: #606266;
  border: 1px solid #dcdfe6;
}
.input {
  width: 100%;
  height: 28px;
  padding: 0 15px;
  box-sizing: border-box;
  border-radius: 4px;
  color: #606266;
  border: 1px solid #dcdfe6;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
input[type='number'] {
  -moz-appearance: textfield;
}
</style>
